﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace SequentialPattern.BasicClass
{
    /// <summary>
    /// 所有顧客的交易資訊
    /// </summary>
    public class CustomersTransaction : Collection<CustomerSequence>
    {
        /// <summary>
        /// 將某個顧客的交易時間與產品加入
        /// </summary>
        /// <param name="cid">顧客編號</param>
        /// <param name="tid">交易時間</param>
        /// <param name="pid">交易產品</param>
        public void Add(string cid, int tid, Item pid)
        {
            List<CustomerSequence> customer = (from cs in this where cs.CustomerID == cid select cs).ToList<CustomerSequence>();

            if (customer.Count == 0)
            {
                CustomerSequence tmpCS = new CustomerSequence();
                tmpCS.CustomerID = cid;
                tmpCS.Add(tid, pid);
                this.Add(tmpCS);
            }
            else
            {
                customer[0].Add(tid, pid);
            }
        }

        /// <summary>
        /// 將所有交易資訊依照(顧客編號, 交易時間, 交易產品)排序好
        /// </summary>
        public void Sort()
        {
            IEnumerable<CustomerSequence> customerSequence = this.OrderBy<CustomerSequence, string>(cs => cs.CustomerID);
            int count = 0;
            foreach (CustomerSequence cs in customerSequence)
            {
                cs.Sort();
                this[count] = cs;
                ++count;
            }
        }

        /// <summary>
        /// 取得交易下所有的項目集
        /// </summary>
        /// <returns>所有項目集的集合</returns>
        public List<ItemSet> GetAllItemSets()
        {
            List<ItemSet> result = new List<ItemSet>();

            foreach (Sequence sequence in this)
            {
                foreach (ItemSet itemSet in sequence)
                {
                    /* 為項目集下的每個item檢查 */
                    foreach (Item item in itemSet)
                    {
                        ItemSet tmpSet = new ItemSet();
                        tmpSet.Add(item);
                        if (!result.Contains(tmpSet)) result.Add(tmpSet);
                    }
                    /* 為整個項目集檢查 */
                    if (!result.Contains(itemSet)) result.Add(itemSet);
                }
            }
            result = result.OrderBy<ItemSet, string>(r => r.ToString()).OrderBy<ItemSet, int>(r => r.Count).ToList<ItemSet>();
            // IEnumerable<ItemSet> tmp = (from r in result orderby r.Count, r.ToString() select result);
            return result;
        }
    }
}
